//
//  FMNetwork.m
//  WindRunner
//
//  Created by leeqb on 6/10/14.
//
//

#import "FMNetwork.h"

@implementation FMNetwork

+ (void)request:(FMRequestObject *)requestObj showMask:(BOOL)showMask success:(void (^)(NSDictionary *data))success falied:(void (^)(NSError *error))failed
{
    FMNetwork *newwork = [[FMNetwork alloc] init];
    newwork.requestObj = requestObj;
    newwork.showMask = showMask;
    newwork.success = (__bridge void (^)(NSDictionary *__strong))(CFBridgingRetain(success));
    newwork.failed = (__bridge void (^)())(CFBridgingRetain(failed));
    [newwork start];
}

- (void)start
{
    [self showMessage:@"努力加载中..."];
    
    NSMutableString *paramsString = [NSMutableString string];
    if(self.requestObj.params.allKeys.count > 0) {
        for(NSString *key in self.requestObj.params.allKeys) {
            [paramsString appendFormat:@"%@=%@&", key, self.requestObj.params[key]];
        }
        
        paramsString = [[paramsString substringToIndex:(paramsString.length-1)] mutableCopy];
        paramsString = [[paramsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];
    }
    NSLog(@"%@%@?%@", self.requestObj.baseURL, self.requestObj.interface, paramsString);
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", self.requestObj.baseURL, self.requestObj.interface]]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[paramsString dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
}

// 避免每个地方都去加判断
- (void)showMessage:(NSString *)message
{
    if(self.showMask) {
        [FMToast showLoading:message];
    }
}

// 请求成功回调
- (void)callbackSuccess:(NSDictionary *)result
{
    if(_success) {
        _success(result);
        CFBridgingRetain(result);
    }
}

// 请求失败回调
- (void)callbackFailed:(NSError *)error
{
    if(_failed) {
        _failed(error);
        CFBridgingRetain(_failed);
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _response = response;
    _data = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [FMToast showMessage:@"请求失败"];
    [self callbackFailed:error];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if(self.showMask) {
        [FMToast hide];
    }
    
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)_response;
    if(httpResponse.statusCode == 200) {
        NSString *dataString = [[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];
        NSData *shareContentData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
        
        // 当msg为“请重新登录”时，表示令牌过期，需要重新登录
        
        // 将json字符串转换成NSDictionary对象
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:shareContentData options:kNilOptions error:&err];
        
        BOOL success = [result[@"success"] boolValue];
        if(success) {
            [self callbackSuccess:result];
        } else {
            [self callbackFailed:[NSError errorWithDomain:@"Result Error" code:httpResponse.statusCode userInfo:result]];
        }
    } else {
        [self callbackFailed:[NSError errorWithDomain:@"connectionDidFinishLoading Error" code:httpResponse.statusCode userInfo:nil]];
    }
}

@end
